import 'package:flutter/material.dart';
import '../../models/serach_info_model.dart';
import 'package:ninetyfour/l10n/app_localizations.dart';

class ProductChongView extends StatefulWidget {
  final List<TypeListModel>? rechargeTypeList;
  final Function(int, int)? onSelect;

  const ProductChongView({
    super.key,
    required this.rechargeTypeList,
    this.onSelect,
  });

  @override
  State<ProductChongView> createState() => _ProductChongViewState();
}

class _ProductChongViewState extends State<ProductChongView> {
  int selectPath = 0;
  int selectIndex = 0;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (widget.rechargeTypeList?.isEmpty ?? true) return;
      final selectedIndex = widget.rechargeTypeList!.indexWhere((element) => element.select == 1);
      if (selectedIndex != -1) {
        setState(() {
          selectPath = selectedIndex;
          selectIndex = widget.rechargeTypeList![selectedIndex].spuList.indexWhere((e) => e.select == 1);
        });
        widget.onSelect?.call(selectPath, selectIndex);
      }
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (widget.rechargeTypeList?.isEmpty ?? true) return;
      final selectedIndex = widget.rechargeTypeList!.indexWhere((element) => element.select == 1);
      if (selectedIndex != -1 && selectPath != selectedIndex) {
        setState(() {
          selectPath = selectedIndex;
          selectIndex = widget.rechargeTypeList![selectedIndex].spuList.indexWhere((e) => e.select == 1);
        });
       widget.onSelect?.call(selectPath, selectIndex);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    if (widget.rechargeTypeList?.isEmpty ?? true) {
      return Center(child: CircularProgressIndicator());
    }
    return Container(
      margin: const EdgeInsets.only(top: 15, left: 15, right: 15),
      // 修改为在 decoration 中设置颜色
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 第一部分：商品名称
          _buildSectionTitle(AppLocalizations.of(context)!.rechargeType),
          // 第二部分：横向按钮列表
          _buildHorizontalButtonList(),
          // 第三部分：商品面值
          _buildSectionTitle(AppLocalizations.of(context)!.faceValue),
          // 第四部分：网格布局
          _buildGridLayout(),
          SizedBox(height: 15)
        ],
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
      child: Text(
        title,
        style: const TextStyle(
          color: Color(0xFF2A2A2A),
          fontSize: 14,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }

Widget _buildHorizontalButtonList() {
  return Padding(
    padding: const EdgeInsets.only(left: 15, right: 15), // 左右各15的间距
    child: SizedBox(
      width: MediaQuery.of(context).size.width - 30, // 父容器宽度固定
      child: Wrap(
        spacing: 10, // 横向间距
        runSpacing: 10, // 纵向间距
        children: List.generate(widget.rechargeTypeList?.length ?? 0, (index) {
          final item = widget.rechargeTypeList![index];
          final isSelected = index == selectPath;

          return GestureDetector(
            onTap: () {
              WidgetsBinding.instance.addPostFrameCallback((_) {
                setState(() {
                  selectPath = index;
                  selectIndex = 0;
                });
                widget.onSelect?.call(selectPath, selectIndex);
              });
            },
            child: Container(
              width: (MediaQuery.of(context).size.width - 80) / 3, // 每个子项的宽度
              // height: 38,
              padding: const EdgeInsets.symmetric(horizontal: 3,vertical: 3),
              decoration: BoxDecoration(
                color: isSelected ? const Color(0xFFF7F7FF) : const Color(0xFFF6F6F6),
                borderRadius: BorderRadius.circular(10),
                border: isSelected ? Border.all(color: const Color(0xFF5D5FEE)) : null,
              ),
              alignment: Alignment.center,
              child: Text(
                item.name,
                textAlign: TextAlign.center, // 显式设置居中
                style: TextStyle(
                  color: isSelected ? const Color(0xFF5D5FEE) : const Color(0xFF2A2A2A),
                  fontSize: 13,
                ),
                maxLines: 2, // 明确限制最大行数
                overflow: TextOverflow.ellipsis, // 超出部分显示省略号
              ),
            ),
          );
        }),
      ),
    ),
  );
}


 Widget _buildGridLayout() {
  final spuList = widget.rechargeTypeList?[selectPath].spuList ?? [];

  return Padding(
    padding: const EdgeInsets.symmetric(horizontal: 15),
    child: Wrap(
      spacing: 10, // 横向间距
      runSpacing: 20, // 纵向间距
      children: List.generate(spuList.length, (index) {
        final item = spuList[index];
        // Removed inline setState call during build
        final isSelected = index == selectIndex;
        return GestureDetector(
          onTap: () {
            WidgetsBinding.instance.addPostFrameCallback((_) {
              setState(() => selectIndex = index);
              widget.onSelect?.call(selectPath, selectIndex);
            });
          },
          child: Stack(
            clipBehavior: Clip.none,
            children: [
              Container(
                width: (MediaQuery.of(context).size.width - 80) / 3, // 每个 item 的宽度，减去左右 padding 并均分
                // height: 40, // 固定高度
                decoration: BoxDecoration(
                  color: isSelected ? const Color(0xFFF7F7FF) : const Color(0xFFF6F6F6),
                  borderRadius: BorderRadius.circular(10),
                  border: isSelected ? Border.all(color: const Color(0xFF5D5FEE)) : null,
                ),
                child: Padding(
                  padding: const EdgeInsets.symmetric(vertical: 8,horizontal: 3),
                  child: Text(
                    item.attrvalue,
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: isSelected ? const Color(0xFF5D5FEE) : const Color(0xFF2A2A2A),
                      fontSize: 13,
                    ),
                  ),
                ),
              ),
            if (item.tag.isNotEmpty)
              Positioned(
                left: -5,
                top: -5,
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                  decoration: BoxDecoration(
                    borderRadius: const BorderRadius.only(
                      topLeft: Radius.circular(7),
                      bottomRight: Radius.circular(7),
                    ),
                    gradient: const LinearGradient(
                      colors: [Color(0xFFD913FB), Color(0xFFFD2E59)],
                      begin: Alignment.centerLeft,
                      end: Alignment.centerRight,
                    ),
                  ),
                  child: Text(
                    item.tag,
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 10,
                      height: 1,
                    ),
                  ),
                ),
              ),
          ],
        ),
      );
      }),
    ),
  );
}

}